import { Button, Dialog, Form, Input, Message, Divider } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useRef, useState, useEffect } from 'react';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { FieldsGrid } from '../stores/definitions';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import ChargeForm from './ChargeForm';

const FromItem = Form.Item;
const tableId = uniqueId('tauTable-');

const BatchApply = ({ coupon, visible, onSubmit, onCancel, modal }) => {
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [formData] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current;
  const { couponStore: store } = useStore();
  const [curCharge, setCurCharge] = useState();
  const [idx, setIdx] = useState(-1);
  const [users, setUsers] = useState([]);
  const [currentUser, setCurrentUser] = useState([]);
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    const { applyInfos } = coupon;
    setCurrentUser(applyInfos || []);
    _.assign(formData, coupon);
    setUsers(applyInfos || []);
  }, [visible]);

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = users?.slice(startIndex, endIndex);

  const overrideModel = {
    addUser: {
      label: t`添加客户`,
      ui: {
        renderer: () => (
          <Input
            style={{ width: 300 }}
            placeholder="请输入手机号"
            addonAfter={<Button type="primary" onClick={handleAddUser}>{t`添加客户`}</Button>}
          />
        ),
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);

    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleAddUser = async () => {
    const { addUser } = formData;
    if (!addUser) {
      return Message.warning({ content: t`请输入手机号!` });
    }
    if (addUser.length !== 11) {
      return Message.warning({ content: t`请输入正确手机号!` });
    }
    try {
      const findUser = users.find((p) => p.username === addUser);
      if (findUser) {
        return Message.warning({ content: t`该手机号已存在!` });
      }
      const res = await store.getUserMobile(addUser);
      if (res) {
        const { mobile: username, fullname: name } = res;
        setUsers((pre) => {
          const arr = [...pre];
          arr.push({ name, username, number: 10 });
          return arr;
        });
      } else {
        Message.error({ content: t`该用户非平台用户!` });
      }
    } catch (error) {
      Message.error({ content: t`添加失败`, duration: 7000 });
      throw error;
    }
  };

  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    setUsers((pre) => {
      const newCharge = [...pre];
      newCharge[idx] = values;
      return newCharge;
    });
    setCurCharge(false);
  };

  const handleDeleteState = (i) => {
    setUsers((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const handleCurCharge = (values) => {
    setCurCharge({
      values,
    });
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { batchId } = formData;
    const filterUsers = users.filter((item) => !currentUser.some((otherItem) => otherItem.username === item.username));
    const params = {
      batchId,
      applyInfos: filterUsers,
    };
    onSubmit?.(params);
  };

  return (
    <Form
      colon
      value={formData}
      {...formProps}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={formData}
        mode={modal[0]}
        columns={1}
        overrideModel={overrideModel}
        fields={['addUser']}
      />
      <FromItem
        label={t`白名单列表`}
        labelAlign="top"
        name="listUser"
      >
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="auto"
          currentPage={currentPage}
          pageSize={pageSize}
          total={users.length}
          onFetch={({ page, size }) => {
            setCurrentPage(page);
            size && setPageSize(size);
          }}
          dataSource={currentPageData}
          onRowClick={(_, index) => setIdx(index)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.priceIdx(i, currentPage, pageSize) },
            {
              title: t`姓名`,
              dataIndex: 'name',
              width: 80,
              align: 'center',
            },
            {
              title: t`手机号`,
              dataIndex: 'username',
              width: 160,
              align: 'center',
            },
            {
              title: t`数量`,
              dataIndex: 'number',
              width: 80,
              align: 'center',
            },
            {
              title: t`操作`,
              dataIndex: '',
              width: 180,
              cell: (v, i, r) => (
                <>
                  <Button type="primary" text onClick={() => handleCurCharge(r)}>{t`编辑`}</Button>
                  <Divider direction="ver" />
                  <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i)}>{t`删除`}</Button>
                </>
              ),
            },
          ]}
        />
      </FromItem>
      <DrawerFooter>
        <FromItem>
          {<Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <Dialog
        visible={!!curCharge}
        onCancel={() => setCurCharge(false)}
        onClose={() => setCurCharge(false)}
        title={t`编辑内容`}
        style={{ width: '30%' }}
        footer={null}
      >
        <ChargeForm
          data={curCharge}
          onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
          onCancel={() => setCurCharge(false)}
        />
      </Dialog>
    </Form>
  );
};

export default observer(BatchApply);
